<?php

namespace app\api\controller;

use app\admin\model\Sendauto;
use app\admin\model\Withdraw;
use app\common\controller\Api;
use app\admin\model\Send;
use app\admin\model\Location;
use app\admin\model\Record;
use addons\epay\library\Service;
use app\common\model\MoneyLog;


class Profile extends Api
{
    protected $noNeedLogin = ['openDoor'];
    protected $noNeedRight = ['*'];
    /**
     * 业主发布
     * Summary of send
     * @return void
     */
    public function send()
    {
        $user = $this->auth->getUserinfo();
        if($user['group_id'] != 1) {
            $this->error('业主才能发布');
        }
        $beginTime = $this->request->post('beginTime','');
        $endTime =  $this->request->post('endTime','');
        $locationId = $this->request->post('locationId','');
        if(empty($beginTime) || !$endTime || !$locationId) $this->error('参数错误');
        $detail = Location::find($locationId);
        if(empty($detail)) $this->error('车位有误');
        if($detail['user_id'] != $this->auth->id) {
            $this->error('只能发布自己的车位');
        }
        if( $detail['status'] == 1) $this->error('车位正在使用，无法发布');
        Send::insert(['date' => date('Y-m-d',strtotime($beginTime)) ,'begin_time' => strtotime( $beginTime),'end_time' =>  strtotime( $endTime),'user_id' => $this->auth->id,'location_id' => $locationId,'location' => $detail['location']]);
        $this->success('suc');
        
    }
    /**
     * 我的车位
     * Summary of myLocation
     * @param mixed $page
     * @return void
     */
    public function myLocation($page = 1)
    {
        $user = $this->auth->getUserinfo();
        if($user['group_id'] != 1) {
            $this->error('不是业主');
        }
        $list = Location::where(['user_id' => $this->auth->id])->paginate(20,false,['page' => $page]);
        $list->each(function($item){
            $item['detail'] = '';
            if($item['status'] == 1) {//如果=1就是在使用中
                
                $detail=  Record::where(['location_id'=> $item['id'],'status' => ['in',[1,2]]])->field('begin_time,num,pay_time,end_time')->find();
                $detail['num'] = str_repeat('*', 3) . substr( $detail['num'], 3);
                $item['detail'] = $detail;
            }
        });
        $this->success('suc',$list);
    }
    public function record($page = 1,$status = 4,$option = '')
    {
        $user = $this->auth->getUserinfo();
        if($user['group_id'] != 1) {
            $this->error('业主才能操作');
        }
        $where['master_id'] =  $this->auth->id;
        if($status != 4) {
            $where['status'] = $status;
        }
        if($option) {
           $where['num'] = ['LIKE',"%$option%"];
        }
        $list = Record::where($where)->paginate(20,false,['page' => $page])->each(function($item){
            $detail = Location::find($item['location_id']);
            $item['locationName'] =  $detail['location']; 
        });
        $this->success('suc',$list);
    }
    /**
     * 去预约
     * @return void
     */
    public function prepare()
    {
        $carNum = $this->request->post('num','');//车牌号
        $locationId = $this->request->post('locationId','');//地址ID
        $detail = Location::find($locationId);
    
        if(empty($detail)) $this->error('fail');
        $repeat = Record::where(['user_id' => $this->auth->id,'date' => date('Y-m-d'),'location_id' => $locationId,'num' => $carNum,'status' => 0])->find();
        if($repeat) {
            $this->error('重复预约');
        }
        $isFree = Record::where(['location_id' => $locationId,'status' => ['in',[1,2]]])->find();
        if($isFree)  $this->error('该车位已被预约');
        $insertData = [
            'location_id' =>  $locationId,
            'num' => $carNum,
            'user_id' => $this->auth->id,
            'type' => 0,
            'master_id' => $detail['user_id'],
            'order_id' => Record::generateOrderSn(),
            'money' => $detail['money'],
            'prepare_begin_time' => time() ,
            'location' =>  $detail['location'],
            'date' => date('Y-m-d')
        ];
        $id = \think\Db::name('record')->insertGetId($insertData);
      
        $this->success('suc',['id' =>  $id]);
    }
    /**
     * 预约详情
     * Summary of prepareDetail
     * @return void
     */
    public function prepareDetail($id)
    {
        $detail = Record::find($id);
        $this->success('suc',Record::find($id));
    }
    public function order($page = 1,$status = 4)
    {
        $where['user_id'] = $this->auth->id;
        if($status != 4) {
            $where['status'] = $status;
        }
        $list = Record::where($where)->order('id desc')->paginate(20,false,['page' => $page])->each(function($item){
            $item['prepare_begin_time'] = date('Y-m-d H:i',$item['prepare_begin_time']);
        });
       
        $this->success('suc',$list);
    }
    public function orderDetail($id = '')
    {
        if(empty($id))  $this->error('fail');
        $detail = Record::find($id);
        $detail['prepare_begin_time'] = date('Y-m-d H:i',$detail['prepare_begin_time']);
        $this->success('suc',$detail);
    }
    /**
     * 
     * 支付后才可以预约
     * @param mixed $id
     * @param mixed $locationId
     * @return void
     */
    public function change($id,$locationId)
    {
        $location = Location::find($locationId);
        if($location['status'] == 2) {
            $this->error('车位使用中');
        }
        $hasPay = Record::where(['user_id' => $this->auth->id,'date' => date('Y-m-d'),'status' => ['in',[1,2]]])->find();
        if(!$hasPay) {
            $this->error('支付后才可以预约');
        }
        Record::where(['id' => $id])->update(['location_id' => $locationId,'master_id' => $location['user_id']]);
        $this->success('suc');
    }
    public function pay()
    {
        $orderId = $this->request->post('id');
        $detail = Record::find($orderId);
        if(empty($detail)) $this->error('订单有误');
        $user = $this->auth->getUser();
        $detail['money'] = 0.01;
        $params = [
            'type'         => 'wechat',
            'orderid' => $detail['order_id'],
            'title'        => '停车缴费',
            'amount'       => $detail['money'],
            'method'       => 'miniapp',
            'openid'       => $user['openid'],
            'auth_code'    => '',
            'notifyurl'    => 'https://www.blzhtx.com/api/index/notify',
            'returnurl'    => '',
        ];
        $this->success('suc',Service::submitOrder($params));
        
    }
    //发起提现
    public function withdraw()
    {
        $money = $this->request->post('money');
        $user = $this->auth->getUser();
        if($money > $user['money']) $this->error('余额不足');
        $orderId = Record::generateOrderSn('TX');
        $result = Service::withdraw($orderId,$money,$user['openid']);
        if($result['code'] == 0) {
            $this->error('fail');
        }
      
        $insert = [//记录到提现记录表
            'user_id' => $this->auth->id,
            'order_id' => Record::generateOrderSn('TX'),
            'money' => $money,
            'create_time' => time(),
            'detail' => json_encode($result)
            
        ];
        //减去余额
        MoneyLog::create(['createtime' => time(),'user_id' => $this->auth->id, 'money' => $money, 'before' => $user['money'], 'after' => $user['money'] - $money, 'memo' => '提现申请变更金额']);
        Withdraw::insert($insert);
        $user->money =   $user->money - $money;
        $user->save();
        $this->success('suc',$result);
    }
    public function confirm($id = '')
    {
        $detail = Withdraw::find($id);
        if(empty($detail)) $this->error('fail');
        if($detail['user_id'] != $this->auth->id) $this->error('fail');
        if($detail['status'] == 0) $this->error('审核中');
        if($detail['status'] == 1) $this->error('提现订单被拒绝');
        $this->success('suc', $detail);
    }
    public function withdrawList($page = 1)
    {
        $list = Withdraw::where(['user_id' => $this->auth->id])->order('id desc')->paginate(20,false,['page' => $page]);
        $list->each(function($item){
            $item['date'] = date('Y/m/d',$item['create_time']);
            $item['time'] = date('H:i',$item['create_time']);
        });
        $this->success('suc',$list );
    }
    /**
     * 车位开闸
     * Summary of openDoor
     * @return void
     */
    public function openDoor()
    {
      
        $location = file_get_contents("php://input");
        if(empty($location)) {
            $this->error('fail');
        }
        $location = json_decode($location,true);
        $detail = Location::where(['id' => $location['locationId']])->find();
        if(empty($detail)) {
            $this->error('车位不存在');
        } 
        $detail->status =  $detail->status == 0 ? 1:0;//开闸之后，修改车位的状态

        $detail->save(); 
        //订单状态改为一正在使用
        Record::where(['user_id' => $this->auth->id,'location_id' => $location['locationId'],'status' => 1])->update(['status' => 2]);
       
        // $controller = new \app\api\controller\Notify();
        // $_GET['type'] = 'openDoor';
        // $controller->getResult();
      
        $this->success('suc');
    }
    /**
     * 开闸列表
     * Summary of getOpenlist
     * @return void
     */
    public function getOpenlist()
    {
     
        // 1.只显示自己预约已支付的车位，
        // 2.若是业主还要显示自己的车位，不要显示所有车位，
        // 3.若自己车位被其他人预约，则这里按钮显示开启状态且自己手动关不了，
        // 4.若是自己车位闲置状态，则可以点击开关闸
        $user = $this->auth->getUserinfo();
        if($user['group_id'] == 0) {//如果用户，只显示已经预约的
            $record = Record::where(['user_id' => $this->auth->id,'status' => 1])->select();
            $ids = [];
            foreach ($record as $key => $value) {
                array_push($ids,$value['location_id']);
            }  
            $data = Location::where(['id' => ['in',$ids]])->order('id desc')->paginate(20,false,['page' => 1]);
            $this->success('suc',$data);
        }
        //业主还要显示我预约了的
        $recordList = Record::where(['user_id' => $this->auth->id,'status' => ['in',[1,2]]])->find();
        
        if($recordList) {
            $data = Location::where(['user_id' =>$this->auth->id,'status' => 0])->whereOr(['id' =>  $recordList['location_id']])->order('id desc')->paginate(20,false,['page' => 1]);
        } else{
            $data = Location::where(['user_id' =>$this->auth->id,'status' => 0])->order('id desc')->paginate(20,false,['page' => 1]);
        
        }
      
        $this->success('suc',$data);
    }
    /**
     * 自动发布
     * Summary of autoSend
     * @return void
     */
    public function autoSend()
    {
        $user = $this->auth->getUserinfo();
        if($user['group_id'] != 1) {
            $this->error('业主才能发布');
        }
        $beginTime = $this->request->post('beginTime');//开始时间
        $endTime = $this->request->post('endTime');//结束时间
        $date = $this->request->post('dates');//日期
        if(empty($beginTime ) || !$endTime ||  !$date ) $this->error('fail');
        $dates = explode(',',$date);
        $insertData = [];
        foreach($dates as $value) {
            $insertData[] = [
                'user_id' => $this->auth->id,
                'begin_time' =>  $beginTime,
                'end_time' => $endTime,
                'date' => $value
            ];
        }
      
        Sendauto::where(['user_id' => $this->auth->id])->delete();//先把之前的删了
        Sendauto::InsertAll($insertData);
        
        $this->success('suc');
    }
    public function autoSet()
    {
        //开启或者关闭
        $user = $this->auth->getUser();
        $user->auto_set = $user['auto_set'] == 0 ? 1:0;
        $user->save();
        $this->success('suc');
    }
    public function myAutoSend()
    {
        $list = Sendauto::where(['user_id' => $this->auth->id])->select();
        $returnData = [];
        $dates = [];
        foreach($list as $value) {
            if(empty($returnData)) {
                $returnData['beginTime'] = $value['begin_time'];
                $returnData['endTime'] = $value['end_time'];
            }
            array_push($dates,$value['date']);
        }
        $returnData['dates'] = $dates;
        $this->success('suc',$returnData);
      
    }
    /**
     * Summary of updateStatus
     * @param mixed $id
     * @param mixed $type
     * @return void
     */
    public function updateStatus($id = '',$type = 0)
    {
        
        Record::where(['id' => $id])->update(['status' => $type == 1 ? 2 :3]);
        $detail =   Record::find($id);
        if(empty($detail)) $this->error('fail');
        if($type == 1) {
            $detail->status = 2;
            $detail->begin_time = time();
        } else {
            $detail->status = 3;
            $detail->end_time = time();
            //如果是结束，还要改车位状态
            $location = Location::find($detail['location_id']);
            $location->status = 0;
            $location->save();
        }
        $detail->save();
        $this->success('suc');
    }
    public function del()
    {
        $this->success('suc');
    }
    
    
    
    
}
